package com.atguigu.szdz.dcsyl.service.impl;

import com.atguigu.szdz.dcsyl.dao.ProjectDao;
import com.atguigu.szdz.dcsyl.service.ProjectService;
import com.atguigu.szdz.dcsyl.utils.MapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@Service("projectService")
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private MapperUtils mapperUtils;

    @Autowired
    private ProjectDao projectDao;
    @Override
    public List<Map<String, Object>> getProjectList(Integer currentPage, String keyword) {
        String sql = "";
        if (currentPage == null || currentPage == 0) {
            sql = "select \n" +
                    "  pro.id,\n" +
                    "  pro.project_name,\n" +
                    "  pro.create_date,\n" +
                    "  pro.update_date,\n" +
                    "  pro.createby,\n" +
                    "  pro.updateby,\n" +
                    "  pro.n,\n" +
                    "  pro.vp,\n" +
                    "  pro.vs,\n" +
                    "  pro.H_rect,\n" +
                    "  pro.h_rect,\n" +
                    "  pro.ucs,\n" +
                    "  pro.o,\n" +
                    "  coalesce(array_agg(wi.id order by wi.id), '{}') as well_ids,\n" +
                    "  coalesce(string_agg(wi.well_name, ', '), '无') as well_names\n" +
                    "from dc_project pro\n" +
                    "left join dc_project_well pw on pro.\"id\" = pw.project_id\n" +
                    "left join dc_well_info wi on wi.\"id\" = pw.well_id\n" +
                    "group by \n" +
                    "  pro.id,\n" +
                    "  pro.project_name,\n" +
                    "  pro.create_date,\n" +
                    "  pro.update_date,\n" +
                    "  pro.createby,\n" +
                    "  pro.updateby,\n" +
                    "  pro.n,\n" +
                    "  pro.vp,\n" +
                    "  pro.vs,\n" +
                    "  pro.H_rect,\n" +
                    "  pro.h_rect,\n" +
                    "  pro.ucs,\n" +
                    "  pro.o\n" +
                    "  order by pro.id asc";
        }else {
            sql="select \n" +
                    "  pro.id,\n" +
                    "  pro.project_name,\n" +
                    "  pro.create_date,\n" +
                    "  pro.update_date,\n" +
                    "  pro.createby,\n" +
                    "  pro.updateby,\n" +
                    "  pro.n,\n" +
                    "  pro.vp,\n" +
                    "  pro.vs,\n" +
                    "  pro.H_rect,\n" +
                    "  pro.h_rect,\n" +
                    "  pro.ucs,\n" +
                    "  pro.o,\n" +
                    "  coalesce(array_agg(wi.id order by wi.id), '{}') as well_ids,\n" +
                    "  coalesce(string_agg(wi.well_name, ', '), '无') as well_names\n" +
                    "from dc_project pro\n" +
                    "left join dc_project_well pw on pro.\"id\" = pw.project_id\n" +
                    "left join dc_well_info wi on wi.\"id\" = pw.well_id\n" +
                    "where (pro.project_name like '%" + keyword + "%')" +
                    "group by \n" +
                    "  pro.id,\n" +
                    "  pro.project_name,\n" +
                    "  pro.create_date,\n" +
                    "  pro.update_date,\n" +
                    "  pro.createby,\n" +
                    "  pro.updateby,\n" +
                    "  pro.n,\n" +
                    "  pro.vp,\n" +
                    "  pro.vs,\n" +
                    "  pro.H_rect,\n" +
                    "  pro.h_rect,\n" +
                    "  pro.ucs,\n" +
                    "  pro.o\n" +
                    "  order by pro.id asc limit 10 offset " + (currentPage - 1) * 10;
        }
        return mapperUtils.queryBySql(sql);
    }

    @Override
    public List<Map<String,Object>> queryForObject(String sql) {
        return mapperUtils.queryBySql(sql);
    }

    @Override
    public void addProject(Map<String, Object> map) {
        // 修复类型转换问题
        Integer[] well_ids;
        Object wellIdObj = map.get("well_id");
        if (wellIdObj instanceof List) {
            List<?> wellIdList = (List<?>) wellIdObj;
            // 过滤并转换为Integer数组
            List<Integer> filteredList = new ArrayList<>();
            for (Object item : wellIdList) {
                if (item instanceof Integer) {
                    filteredList.add((Integer) item);
                } else if (item instanceof Number) {
                    filteredList.add(((Number) item).intValue());
                } else if (item != null && !item.toString().isEmpty()) {
                    try {
                        filteredList.add(Integer.valueOf(item.toString()));
                    } catch (NumberFormatException e) {
                        // 忽略无法转换的项
                    }
                }
            }
            well_ids = filteredList.toArray(new Integer[0]);
        } else if (wellIdObj instanceof Integer[]) {
            well_ids = (Integer[]) wellIdObj;
        } else if (wellIdObj instanceof Object[]) {
            Object[] objArray = (Object[]) wellIdObj;
            List<Integer> filteredList = new ArrayList<>();
            for (Object item : objArray) {
                if (item instanceof Integer) {
                    filteredList.add((Integer) item);
                } else if (item instanceof Number) {
                    filteredList.add(((Number) item).intValue());
                } else if (item != null && !item.toString().isEmpty()) {
                    try {
                        filteredList.add(Integer.valueOf(item.toString()));
                    } catch (NumberFormatException e) {
                        // 忽略无法转换的项
                    }
                }
            }
            well_ids = filteredList.toArray(new Integer[0]);
        } else if (wellIdObj instanceof Integer) {
            well_ids = new Integer[]{(Integer) wellIdObj};
        } else if (wellIdObj != null && !wellIdObj.toString().isEmpty()) {
            try {
                well_ids = new Integer[]{Integer.valueOf(wellIdObj.toString())};
            } catch (NumberFormatException e) {
                well_ids = new Integer[0]; // 无法转换时设为空数组
            }
        } else {
            well_ids = new Integer[0]; // 空值时设为空数组
        }
        LocalDate localDate = LocalDate.now();
        Double n = map.get("n") != null && !map.get("n").toString().isEmpty() ? Double.valueOf(map.get("n").toString()) : 0.0;
        Double vp = map.get("vp") != null && !map.get("vp").toString().isEmpty() ? Double.valueOf(map.get("vp").toString()) : 0.0;
        Double vs = map.get("vs") != null && !map.get("vs").toString().isEmpty() ? Double.valueOf(map.get("vs").toString()) : 0.0;
        Double ucs = map.get("ucs") != null && !map.get("ucs").toString().isEmpty() ? Double.valueOf(map.get("ucs").toString()) : 0.0;
        Double o = map.get("o") != null && !map.get("o").toString().isEmpty() ? Double.valueOf(map.get("o").toString()) : 0.0;
        map.put("n",n);
        map.put("vp",vp);
        map.put("vs",vs);
        map.put("ucs",ucs);
        map.put("o",o);
        map.put("create_date",localDate);
        map.put("update_date",localDate);
        projectDao.insertProject(map);
        //获取项目的主键id
        Integer id = (Integer) map.get("id");
        //添加项目与井的关联关系，只有井id有的时候才添加关联关系
        if (well_ids != null && well_ids.length > 0) {
            for (Integer well_id : well_ids) {
                String sql1 = "insert into dc_project_well (project_id,well_id) values ("+id+","+well_id+")";
                mapperUtils.updataBySql(sql1);
            }
        }
    }

    @Override
    public void updateProject(Map<String, Object> map) {
        Integer id = (Integer) map.get("id");
        String project_name = (String) map.get("project_name");
        // 修复类型转换问题
        Integer[] well_ids;
        Object wellIdObj = map.get("well_ids");
        if (wellIdObj instanceof List) {
            List<Integer> wellIdList = (List<Integer>) wellIdObj;
            well_ids = wellIdList.toArray(new Integer[0]);
        } else {
            well_ids = (Integer[]) wellIdObj;
        }
        String updateby = (String) map.get("updateby");
        Double n = map.get("n") != null && !map.get("n").toString().isEmpty() ? Double.valueOf(map.get("n").toString()) : 0.0;
        Double vp = map.get("vp") != null && !map.get("vp").toString().isEmpty() ? Double.valueOf(map.get("vp").toString()) : 0.0;
        Double vs = map.get("vs") != null && !map.get("vs").toString().isEmpty() ? Double.valueOf(map.get("vs").toString()) : 0.0;
        Double ucs = map.get("ucs") != null && !map.get("ucs").toString().isEmpty() ? Double.valueOf(map.get("ucs").toString()) : 0.0;
        Double o = map.get("o") != null && !map.get("o").toString().isEmpty() ? Double.valueOf(map.get("o").toString()) : 0.0;
        LocalDate localDate = LocalDate.now();
        //先更新项目信息
        String sql = "update dc_project set project_name = '"+project_name+"', n = "+n+", vp = "+vp+", vs = "+vs+", ucs = "+ucs+", o = "+o+", updateby = '"+updateby+"', update_date = '"+localDate+"' where id = "+map.get("id");
        mapperUtils.updataBySql(sql);
        //更新关联信息
        //先删除
        String sql2 = "delete from dc_project_well where project_id = "+id;
        mapperUtils.updataBySql(sql2);
        //再添加
        for (Integer well_id : well_ids) {
            String sql1 = "insert into dc_project_well (project_id,well_id) values ("+id+","+well_id+")";
            mapperUtils.updataBySql(sql1);
        }
    }

    /**
     * 删除项目
     * @param project_id
     */
    @Override
    public void deleteProject(Integer project_id) {
        //先删除关联信息
        String sql1 = "delete from dc_project_well where project_id = "+project_id;
        mapperUtils.updataBySql(sql1);
        //再删除项目信息
        String sql2 = "delete from dc_project where id = "+project_id;
        mapperUtils.updataBySql(sql2);
    }

    @Override
    public List<Map<String, Object>> getWellListByProjectId(Integer project_id) {
        //select wi.* from dc_well_info wi left join dc_project_well pw on wi."id"=pw.well_id where pw.project_id=7
        String sql = "select wi.* from dc_well_info wi left join dc_project_well pw on wi.\"id\"=pw.well_id where pw.project_id = "+project_id;
        return mapperUtils.queryBySql(sql);
    }

    @Override
    public void updateNByProjectId(Map<String, Object> map) {
        Integer project_id = (Integer) map.get("project_id");
        Double n = (Double) map.get("n");
        String sql = "update dc_project set n = "+n+" where id = "+project_id;
        mapperUtils.updataBySql(sql);
    }
}
